package com.unicampmaps;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.FilterQueryProvider;
import android.widget.FrameLayout;
import android.widget.GridView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class ListActivity extends SlidingFragmentActivity {
	
	public FragmentManager mFragmentManager;
	public ListItemAdapter adapter;
	
	public static int curr_type = VenueData.T_SERVICES;
	private List<Venue> venues;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.mFragmentManager = getSupportFragmentManager();
		
		this.venues = new ArrayList<Venue>();

		ActionBar actionBar = this.getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setLogo(R.drawable.actionbar_logo);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_background));

        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setBehindWidthRes(R.dimen.sliding_menu_width);
        slidingMenu.setBehindScrollScale(0.0f);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        setBehindContentView(R.layout.fragment_menu);
        
        
        setContentView(R.layout.activity_list);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_menu, new MenuFragment()).commit();
		
        loadVenues();
        
		Button mapButton = (Button) findViewById(R.id.map_button);
		mapButton.setOnClickListener(new OnClickListener() {
	        
			@Override
			public void onClick(View arg0) {
				BasicMapViewer.emptyVenues();
				for (int i = 0; i < ListActivity.this.venues.size(); i++) {
					BasicMapViewer.addVenue(ListActivity.this.venues.get(i));
				}
				
	        	Intent intent;
    			intent = new Intent(arg0.getContext(), BasicMapViewer.class);
    	        startActivity(intent);
	        }
	    });
	}
	
	
	private void loadVenues(){
		String searchText = getIntent().getStringExtra("search_text");
		if(searchText!=null){
			loadVenuesBySearchText(searchText);
		}else{
			loadVenuesByTag();
		}
	}
	
	private void loadVenuesBySearchText(String text){
		String[] projection = { 
			    VenueData.C_ID,
			    VenueData.C_FOURSQUARE_VENUE_ID,
			    VenueData.C_TYPE,
			    VenueData.C_NAME,
			    VenueData.C_ABBR,
			    VenueData.C_ADDRESS,
			    VenueData.C_LATITUDE, 
			    VenueData.C_LONGITUDE,
			    VenueData.C_PHONE_NUMBER, 
			    VenueData.C_SITE,
			    VenueData.C_IMAGE};
		

        GridView grid = (GridView) findViewById(R.id.gridview);
        this.adapter = new ListItemAdapter(this);
		
        //Busca por tipo de ponto de interesse
		Uri uri = VenueProvider.CONTENT_URI;
		Cursor cursor = getContentResolver().query(uri, projection, 
				VenueData.C_NAME+ " LIKE ? or " +VenueData.C_ABBR +" LIKE ?", 
				new String[]{"%"+text+"%","%"+text+"%"}, null);
		
		if (cursor != null) {
			cursor.moveToFirst();
			
			for (int i = 0; i < cursor.getCount(); i++) {
				int id = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_ID));
				String fourquare_venue_id = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_FOURSQUARE_VENUE_ID));
				int type = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_TYPE));
				String name = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_NAME));
				String abbr = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ABBR));
				String address = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ADDRESS));
				float latitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LATITUDE));
				float longitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LONGITUDE));
				String phone_number = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_PHONE_NUMBER));
				String site = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_SITE));
				String image = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_IMAGE));
		        
				Venue v = new Venue(id, fourquare_venue_id, type, name, abbr, address, latitude, longitude, phone_number, site, image);
				
				this.venues.add(v);
				
		        this.adapter.addItem(v);
		        
		        cursor.moveToNext();
			}
			
			cursor.close();
		}
		

		grid.setAdapter(this.adapter);
		
		grid.setOnItemClickListener(new OnItemClickListener() {
	        @Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
	        	System.out.println("CLICKED ID: " + id);
	        	DetailsActivity.curr_venue_id = id;
	        	
	        	Intent intent;
    			intent = new Intent(arg0.getContext(), DetailsActivity.class);
    	        startActivity(intent);
	        }
	    });
	}

	private void loadVenuesByTag() {
		String[] projection = { 
			    VenueData.C_ID,
			    VenueData.C_FOURSQUARE_VENUE_ID,
			    VenueData.C_TYPE,
			    VenueData.C_NAME,
			    VenueData.C_ABBR,
			    VenueData.C_ADDRESS,
			    VenueData.C_LATITUDE, 
			    VenueData.C_LONGITUDE,
			    VenueData.C_PHONE_NUMBER, 
			    VenueData.C_SITE,
			    VenueData.C_IMAGE};
		

        GridView grid = (GridView) findViewById(R.id.gridview);
        this.adapter = new ListItemAdapter(this);
		
        //Busca por tipo de ponto de interesse
		Uri uri = Uri.parse(VenueProvider.CONTENT_URI + "/" + VenueData.C_TYPE + "/" + ListActivity.curr_type);
		Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
		
		if (cursor != null) {
			cursor.moveToFirst();
			
			for (int i = 0; i < cursor.getCount(); i++) {
				int id = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_ID));
				String fourquare_venue_id = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_FOURSQUARE_VENUE_ID));
				int type = cursor.getInt(cursor.getColumnIndexOrThrow(VenueData.C_TYPE));
				String name = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_NAME));
				String abbr = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ABBR));
				String address = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_ADDRESS));
				float latitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LATITUDE));
				float longitude = cursor.getFloat(cursor.getColumnIndexOrThrow(VenueData.C_LONGITUDE));
				String phone_number = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_PHONE_NUMBER));
				String site = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_SITE));
				String image = cursor.getString(cursor.getColumnIndexOrThrow(VenueData.C_IMAGE));
		        
				Venue v = new Venue(id, fourquare_venue_id, type, name, abbr, address, latitude, longitude, phone_number, site, image);
				
				this.venues.add(v);
				
		        this.adapter.addItem(v);
		        
		        cursor.moveToNext();
			}
			
			cursor.close();
		}
		

		grid.setAdapter(this.adapter);
		
		grid.setOnItemClickListener(new OnItemClickListener() {
	        @Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
	        	System.out.println("CLICKED ID: " + id);
	        	DetailsActivity.curr_venue_id = id;
	        	
	        	Intent intent;
    			intent = new Intent(arg0.getContext(), DetailsActivity.class);
    	        startActivity(intent);
	        }
	    });
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_search, menu);
	    MenuItem searchViewItem = menu.findItem(R.id.menu_search);
	    SearchView searchView = (SearchView) searchViewItem.getActionView();
	    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(350, FrameLayout.LayoutParams.WRAP_CONTENT);
	    searchView.setLayoutParams(lp);

	    searchView.setIconifiedByDefault(false);
	    searchView.setSubmitButtonEnabled(false);
	    
	    AutoCompleteTextView txtView = (AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
	    
	    txtView.setTextColor(Color.BLACK);
	    
	    final int[] to = new int[]{android.R.id.text1};
        final String[] from = new String[]{VenueData.C_NAME};
        VenueCursorAdapter adapter = new VenueCursorAdapter(this, R.layout.autocomplete_item, null, from, to, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        // This will provide the labels for the choices to be displayed in the AutoCompleteTextView
        adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
            @Override
            public CharSequence convertToString(Cursor cursor) {
                final int colIndex = cursor.getColumnIndexOrThrow(VenueData.C_NAME);
                return cursor.getString(colIndex);
            }
        });
        
        adapter.setFilterQueryProvider(new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence description) {
            	if (description == null) {
            		description = "";
            	}
            	String[] projection = new String[]{VenueData.C_ID, VenueData.C_NAME, VenueData.C_ABBR, VenueData.C_IMAGE};
            	String selection = VenueData.C_NAME + " LIKE ? OR " + VenueData.C_ABBR + " LIKE ?";
            	String[] selectionArgs = new String[]{"%" + description.toString() + "%", "%" + description.toString() + "%"};
            	Cursor managedCursor = ListActivity.this.getContentResolver().query(VenueProvider.CONTENT_URI, projection, selection, selectionArgs, null);
            	System.out.println(managedCursor.getCount() + " rows");
                return managedCursor;
            }
        });
        
		txtView.setAdapter(adapter);
		
		txtView.setOnItemClickListener(new OnItemClickListener() { 

		    @Override
		    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
		    	DetailsActivity.curr_venue_id = id;
		        Intent intent = new Intent(arg0.getContext(), DetailsActivity.class);
		        startActivity(intent); 
		    }
		});
		
	    
	    return true;
	}

}
